<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称或路径或ID"
          clearable
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="danger" plain @click="toggleExpandAll">
          <Icon icon="ep:sort" class="mr-5px" /> 展开/折叠
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column prop="name" label="名称" width="360" />
      <el-table-column prop="path" label="访问路径" width="200" />
      <el-table-column prop="modelId" label="栏目模型" width="150">
        <template #default="{ row }">
          <span>{{ channelModelFormat(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="contentModelId" label="内容模型" width="150">
        <template #default="{ row }">
          <span>{{ contentModelFormat(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="100" />

      <el-table-column label="操作" align="center" class-name="fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleRestore(scope.row.id)"
            v-hasPermi="['cms:channel:update']"
          >
            {{ t('cms.menu.channelReStore') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['cms:channel:delete']"
          >
            {{ t('action.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>
</template>
<script setup lang="ts" name="Channel">
import { handleTree } from '@/utils/tree'
import * as ChannelApi from '@/api/cms/channel'
import { getModelList } from '@/api/cms/model/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const loading = ref(true) // 列表的加载中
const list = ref() // 列表的数据
const queryParams = reactive({
  name: undefined
})
const queryFormRef = ref() // 搜索的表单
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const parentOptions = ref() // 树形结构
const channelModelList = ref<any[]>([])
const contentModelList = ref<any[]>([])
const fetchChannelModelList = async () => {
  channelModelList.value = await getModelList(1)
}
const fetchContentModelList = async () => {
  contentModelList.value = await getModelList(2)
}

// 获取下拉框[上级]的数据
const getTree = async () => {
  parentOptions.value = []
  const res = await ChannelApi.listSimpleChannelApi()
  let channel: Tree = { id: 0, name: '顶级栏目', children: [] }
  channel.children = handleTree(res)
  parentOptions.value.push(channel)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ChannelApi.getRecycleChannelListApi(queryParams)
    list.value = handleTree(data)
  } finally {
    loading.value = false
  }
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}
// 还原操作
const handleRestore = async (rowId: number) => {
  ElMessageBox.confirm(t('common.restoreMessage'), t('common.confirmTitle'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  }).then(async () => {
    await ChannelApi.restoreChannelApi(rowId)
    await getList()
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ChannelApi.deleteChannelApi(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

const contentModelFormat = (row) => {
  if (!row || !row.contentModelId) {
    return '未设置'
  }
  for (const model of contentModelList.value) {
    if (row.contentModelId === model.id) {
      return model.name
    }
  }
  return '未知【' + row.contentModelId + '】'
}
const channelModelFormat = (row) => {
  if (!row || !row.modelId) {
    return '未设置'
  }
  for (const model of channelModelList.value) {
    if (row.modelId === model.id) {
      return model.name
    }
  }
  return '未知【' + row.modelId + '】'
}

// ========== 初始化 ==========
onMounted(async () => {
  await fetchChannelModelList()
  await fetchContentModelList()
  await getTree()
  await getList()
})
</script>
<style lang="scss">
.el-row {
  margin-bottom: 10px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.el-col-10,
.sourceSite {
  margin-left: 100px;
}

.matchTitle {
  width: 80%;
}
</style>
